import requests
from baseTools.my_logger import myLog
from config import *

"""该文件是对接口请求的封装"""
class BaseAPI():

    # 1.基础请求
    def my_request(self,method,url,**kwargs):

        # 完整的路径,base_url是config文件定义的
        newUrl = base_url + url

        myLog.info(f"请求方式{method},请求路径{url},请求参数{kwargs}")
        try:
            self.response = requests.request(method=method,url=newUrl,**kwargs)

            if self.response.json()['code'] != 1:
                return myLog.error("请求失败{}".format(self.response.text))
            myLog.info("接口请求成功")
        except:
            myLog.info("接口请求失败，请重试")
            raise

    # 2.获取共享数据token,这个文件封装到conftest.py文件都可以
    def get_token(self,url,username,password):

        params = {
            "username":username,
            "password":password
        }
        myLog.info("请求接口，获取token")
        self.my_request(method="post",url = url,params=params)
        try:
            self.token = self.response.json()['data']

            if self.response.json().get('code') != 1:
                return myLog.error("获取token失败,报错信息{}".format(self.response.text))
            myLog.info("获取token成功,值为{}".format(self.token))

        except:
            myLog.error("获取token失败,报错信息{}".format(self.response.text))
            raise

# api = BaseAPI()
# api.get_token("/login","admin","admin1234")



